<?php


namespace app\admin\controller\gwa;

use app\common\controller\AdminController;
use EasyAdmin\annotation\ControllerAnnotation;
use EasyAdmin\annotation\NodeAnotation;
use think\App;
use think\facade\Db;

/**
 * @ControllerAnnotation(title="商品入库")
 */
class GoodsWarehousing extends AdminController
{

    use \app\admin\traits\Curd;
    protected $sort = [
        'id'   => 'desc',
    ];

    public function __construct(App $app)
    {
        parent::__construct($app);
        $this->model = new \app\admin\model\GoodsWarehousing();
        
    }
    
    /**
     * @NodeAnotation(title="列表")
     */
    public function index()
    {
        if ($this->request->isAjax()) {
            $param = $this->request->param();
           
            list($page, $limit, $where) = $this->buildTableParames();

            $where = [];
            if(!empty($param['receipt_no']) && isset($param['receipt_no']))
            {
                $where[] = [
                    ['receipt_no', '=', $param['receipt_no']],
                ];
            }
      
            if(!empty($param['status_time']) && !empty($param['end_time']))
            {
                $where[] = [
                    ['warehousing_time', 'between', [$param['status_time'],$param['end_time']]],
                ];
            }
            $count = $this->model
                ->where($where)
                ->count();
            $list = $this->model
                ->where($where)
                ->page($page, $limit)
                ->order($this->sort)
                ->select();
                foreach ($list as $k => $v){
                    //分类
                    $good_type = Db::name('good_type')->where('id',$v['good_type_id'])->field('title')->find();
                    if(!empty($good_type)){
                        $v['good_type_name'] = $good_type['title'];
                    }else{
                        $v['good_type_name'] = "";
                    }
                  

                    $list[$k] = $v;
                }
            $data = [
                'code'  => 0,
                'msg'   => '',
                'count' => $count,
                'data'  => $list,
            ];
            return json($data);
        }
        $good_type = Db::name("good_type")->order("id desc")->select()->toArray();
        $this->assign("good_type",$good_type);
        return $this->fetch();
    }


    /**
    * @NodeAnotation(title="添加")
    */
    public function add()
    {
        if ($this->request->isAjax()) {
            $session = session("admin");
            $post = $this->request->param();
            if(empty($post['status'])){
                $this->error('入库状态不能为空');
            }
            if(empty($post['goodsw_item'])){
                $this->error('入库商品不能为空');
            }
            if(empty($post['tracking_numberkd'])){
                $this->error('快递单号不能为空');
            }
            $safg = Db::name("goods_warehousing")->where("tracking_numberkd",$post['tracking_numberkd'])->find();
            if(!empty($safg)){
                $this->error('快递单号已存在');
            }
            $goodsw_item = $post['goodsw_item'];
            $data = [
                'receipt_no'=>$post['receipt_no'],
                'receipt_name'=>$post['receipt_name'],
                'receipt_type'=>1,
                'receipt_username'=>$post['receipt_username'],
                'receipt_id'=>$post['receipt_id'],
                'warehousing_time'=>$post['warehousing_time'],
                'status'=>$post['status'],
                'tracking_numberkd'=>$post['tracking_numberkd'],
            ];
            try {
                $save = Db::name("goods_warehousing")->insert($data);
                $goodsw_id = Db::name('goods_warehousing')->getLastInsID();
               
                //添加入库商品信息 
                foreach($goodsw_item as $k=>$v){
                    $v["goods_warehousing_id"] = $goodsw_id;
                    $goodsw_item[$k] = $v;
                }
                Db::name('goods_warehousing_item')->insertAll($goodsw_item); 
                $admin = Db::name("system_admin")->where("id",$session["id"])->find();
                if($post['status'] == 2){
                    foreach($goodsw_item as $k=>$ve){
                        //添加出入库明细
                        $data_crk = [
                            "data_id"=>$goodsw_id,//数据id
                            'odd_numbers'=>$post["receipt_no"],//单号
                            "gid"=>$ve["gid"],
                            "good_type_id"=>$ve["good_type_id"],
                            "good_type_name"=>$ve["good_type_name"],
                            "receipt_issue_type"=>1,//1采购入库 2作废入库 3销售出库 4盘赢入库 5盘亏出库
                            "create_time"=>time(),
                            "receipt_issue_num"=>$ve["num"], //出入库数量 
                            "tracking_numbercr"=>$post["tracking_numberkd"],
                            "discrepancy"=>$admin["employee_name"], //出入库员
                        ];
                        Db::name("receipt_issue_detailed")->insert($data_crk);
                        //修改商品库存
                        Db::name("goods")->where("id",$ve["gid"])->inc("stock",$ve["num"])->update();
                    }
                }
              
            } catch (\Exception $e) {
                $this->error('保存失败:' . $e->getMessage());
            }
            $save ? $this->success('保存成功') : $this->error('保存失败');
        }else{
            return $this->fetch();
        }
       
    }

    //新建入库基础数据
    public function incoming_data(){
        $session = session("admin");
        //入库单号
        $receipt_no = date('Ymd') . substr(implode(null, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8).$session['id'];

        $warehousing_time = date("Y-m-d H:i:s",time());

        $receipt_username = $session["username"];//入库人姓名
        $receipt_id = $session["id"];//入库人id
        
        $res = [
            "receipt_no"=>$receipt_no,
            "warehousing_time"=>$warehousing_time,
            "receipt_username"=>$receipt_username,
            "receipt_id"=>$receipt_id,
        ];
        return json([
            "code"=>1,
            "data"=>$res
        ]);
    }

    //根据商品条码获取商品
    public function get_tmgood(){
        if ($this->request->isAjax()) {
            $param = $this->request->param();
            if(!empty($param['bar_code']) || !empty($param['bar_code']))
            {
                $where[] = [
                    //['bar_code', '=', $param['bar_code']]
                    ['bar_code', 'like', "%{$param['bar_code']}%"]
                ];
            }
            if(!empty($param['good_name']) || !empty($param['good_name']))
            {
                $where[] = [
                    ['title', '=', $param['good_name']]
                ];
            }
            if(empty($where)){
                $this->success("商品不存在",[]);
            }
            $goods = Db::name("goods")->where("status",0)->where($where)->field("id,good_type_id,title,bar_code,status")->find();
            if(empty($goods)){
                $this->error('商品不存在',[]);
            }
            $good_type =  Db::name("good_type")->where("id",$goods["good_type_id"])->find();
            $goods["good_type_name"] = $good_type["title"];
            $this->success('获取成功',$goods);
        }
    }

     /**
    * @NodeAnotation(title="编辑")
    */
    public function edit()
    {
        if ($this->request->isAjax()) {
            $post = $this->request->param();
            if(empty($post['goodsw_item'])){
                $this->error('入库商品不能为空');
            }
            if(empty($post['status'])){
                $this->error('入库状态不能为空');
            }
            $goodsw_item = $post['goodsw_item'];
            $data = [
                'status'=>$post['status'],//状态（1入库中，2入库完成）
                'receipt_name'=>$post['receipt_name'],
            ];
            try {
               $this->model->where('id',$post['id'])->update($data);
              
                //删除入库详情重新入库
                Db::name('goods_warehousing_item')->where("goods_warehousing_id",$post["id"])->delete();
                Db::name('goods_warehousing_item')->insertAll($goodsw_item); 
                if($post['status'] == 2){
                    foreach($goodsw_item as $k=>$ve){
                        //添加出入库明细
                        $data_crk = [
                            "data_id"=>$post["id"],//数据id
                            'odd_numbers'=>$post["receipt_no"],//单号
                            "gid"=>$ve["gid"],
                            "good_type_id"=>$ve["good_type_id"],
                            "good_type_name"=>$ve["good_type_name"],
                            "receipt_issue_type"=>1,//1采购入库 2作废入库 3销售出库 4盘赢入库 5盘亏出库
                            "create_time"=>time(),
                            "receipt_issue_num"=>$ve["num"] //出入库数量  physical_inventory
                        ];
                    Db::name("receipt_issue_detailed")->insert($data_crk);
                     //修改商品库存
                     Db::name("goods")->where("id",$ve["gid"])->inc("stock",$ve["num"])->update();
               }
             
            }
          
            } catch (\Exception $e) {
                $this->error('保存失败:' . $e->getMessage());
            }
            $this->success('保存成功') ;
        }else{
            $post = $this->request->param(); 
            $row = $this->model->where('id',$post['id'])->find();
            $goods_warehousing_item = Db::name("goods_warehousing_item")->where('goods_warehousing_id',$post['id'])->select()->toArray();
            $this->assign("goods_warehousing_item",$goods_warehousing_item);
            $this->assign('row', $row);
        }
        return $this->fetch();
    }

    //编辑备注
    public function edit_remark(){
        if ($this->request->isAjax()) {
            $post = $this->request->param();
            if(empty($post['reamark'])){
                $this->error('参数不能为空');
            }
            Db::name("goods_warehousing")->where("id",$post["id"])->update(["reamark"=>$post["reamark"]]);
            $this->success('编辑成功');
        }else{
            return $this->fetch();
        }
    }

    //入库详情
    public function goodw_detail(){
        $param = $this->request->param();
        $row = Db::name("goods_warehousing")->where("id",$param["id"])->find();
 
        $goods_warehousing_item = Db::name("goods_warehousing_item")->where("goods_warehousing_id",$param["id"])->select()->toArray();
        
        $row["goods_warehousing_item"] = $goods_warehousing_item;
       // $this->assign("row",$row);
        return json(["code"=>1,"row"=>$row]);
    }


       

    
 
} 